﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using UnityEngine.UI;

public class SocketState
{
    public Socket socket;
    public byte[] buffer;

    public Action<byte[]> ResvMsg;
    public SocketState(Socket socket, Action<byte[]> ResvHandler)
    {
        buffer = new byte[1024];
        this.socket = socket;

        ResvMsg = ResvHandler;
    }

    void RecvCallback(IAsyncResult ar)
    {
        //  Debug.Log("a22222222222222");
        if (ResvMsg != null)
            ResvMsg(buffer);
        string tmpStr = Encoding.Default.GetString(buffer);
        Debug.Log("resv="+ tmpStr);
        BeginSend(tmpStr);
    }
    public void BeginRecv()
    {
        socket.BeginReceive(buffer, 0, 1024, SocketFlags.None, RecvCallback, this);
    }


    public void BeginSend(string tmpStr)
    {
        byte[] data = Encoding.Default.GetBytes(tmpStr);
        socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendBack), this);
    }

    void SendBack(IAsyncResult ar)
    {
        int byteSend = socket.EndSend(ar);
        Debug.Log("byte send count=" + byteSend);
    }
}

public class NetServer : MonoBehaviour
{
    private Socket serverSocket;

    public Text UIText;
    bool isRunding = true;
    byte[] buffer = new byte[1024];
    List<SocketState> ClientSocketList;

    Thread ListenThread;
    void Start()
    {
        InitialSocket();
    } 
    private void ListenRecv()
    {
        while (isRunding)
        {
            try
            {
                serverSocket.BeginAccept(new AsyncCallback(AsyncConnect), serverSocket);
            }
            catch (Exception ec)
            {

            }
        }
        Thread.Sleep(1000);
    }

    private void AsyncConnect(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        Socket clientSocket = listener.EndAccept(ar);
        Debug.Log("sssssssssssssss");
        SocketState state = new SocketState(clientSocket, ResvHandler);
        ClientSocketList.Add(state);
    }

    private void ResvHandler(byte[] bytes)
    {
        //   int len = bytes.Length;
        string tmpStr = Encoding.Default.GetString(buffer);
        Debug.Log("server recv=" + tmpStr);
        // UIText.text += "\n" + tmpStr;

    }

    public void InitialSocket()
    {
        ClientSocketList = new List<SocketState>();
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 18010);
        serverSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        serverSocket.Bind(endPoint);
        serverSocket.Listen(100);

        ListenThread = new Thread(ListenRecv);
        ListenThread.Start();
    }

    void OnApplicationQuit()
    {
        ListenThread.Abort();
        if (serverSocket.Connected)
        {
            serverSocket.Shutdown(SocketShutdown.Both);
            serverSocket.Close();
        }
    }
    void Update()
    {
        if (ClientSocketList.Count > 0)
        {
            for (int i = 0; i < ClientSocketList.Count; i++)
            {
                ClientSocketList[i].BeginRecv();
            }
        }
    }
}
